<?php
use WDB\Query\Element;

class VypujckyTW extends WDB\Wrapper\Table
{
    public function __construct(WDB\Analyzer\iTable $tableAnalyzer)
    {
        parent::__construct($tableAnalyzer);
        $this->addValidator(new CanBorrowValidator());
    }
}

class CanBorrowValidator implements WDB\Validation\iValidator
{
    
    public function fetchValidatorData(WDB\Wrapper\iRecord $record, &$data)
    {
    }
    
    private function validateAge(WDB\Wrapper\iRecord $record)
    {
        switch ($record['fk_vypujcka_titul']['vek']) {
            case '15+':
                $vek = 15;
                break;
            case '18+':
                $vek = 18;
                break;
            default:
                $vek = 0;
                break;
        }
        
        if ($record['fk_vypujcka_zakaznik'] === NULL || date('Y') - $record['fk_vypujcka_zakaznik']['datum_narozeni']->format('Y') < $vek)
        {
            $msg = "Tento titul si mohou půjčit jen zákazníci starší $vek let!";
            $columns = $record->getTable()->getColumns();
            $column = $columns['fk_vypujcka_titul'];
            $record->getField('fk_vypujcka_titul')->addValidationError($msg);
            $record->addValidationErrors(array(array(
                'message'=> $msg,
                'column'=> $column,
            )));
            return false;
        }
        return true;
    }
    private function validateAvailability(WDB\Wrapper\iRecord $record)
    {
        if (!$record->getField('fk_vypujcka_titul')->isChanged()) return true;
        
        $availability = new WDB\Query\Select('id_titul', 'volne_tituly',
                $e=Element\Compare::Equals(
                        Element\ColumnIdentifier::create('id_titul'),
                        new Element\Datatype\Integer($record->getField('fk_vypujcka_titul')->value['id_titul']))
                );
        if ($availability->count() == 0)
        {
            $msg = 'Všechny exempláře tohoto titulu jsou vypůjčené!';
            $columns = $record->getTable()->getColumns();
            $column = $columns['fk_vypujcka_titul'];
            $record->getField('fk_vypujcka_titul')->addValidationError($msg);
            $record->addValidationErrors(array(array(
                'message'=> $msg,
                'column'=> $column,
            )));
            return false;
        }
        return true;
    }
    
    public function raise(WDB\Wrapper\iRecord $record = NULL)
    {
        if ($record['fk_vypujcka_titul'])
        {
            $age = $this->validateAge($record);
            $avail = $this->validateAvailability($record);
            return $age && $avail;
        }
        else
        {
            return true;
        }
    }
}